package com.jml.zlhq.app.ui;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.LoginActivity.AfterDo;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.MD5;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;

public class RegisterActivity extends BaseActivity {
	private EditText phone,vcode,passwd;
	private TextView msg,havazh;
	private Button getVcode,vcodeTime,submit;
	@SuppressWarnings("unused")
	private String vcodeStr;
	private int time60 = 60;
	private boolean getvd = false;
	@SuppressLint("HandlerLeak") 
	private Handler mHandler = new Handler(){
		@Override
		public void dispatchMessage(Message msg) {
			if(time60>0){
				vcodeTime.setText(time60+" 秒后重新发送");
				time60--;
				sendEmptyMessageDelayed(1, 1000);
			}else{
				vcodeTime.setText("重新获取验证码");
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("注册");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		
		phone = (EditText) findViewById(R.id.regidter_phone);
		vcode = (EditText) findViewById(R.id.regidter_vcode);
		passwd = (EditText) findViewById(R.id.regidter_password); 
		msg = (TextView) findViewById(R.id.regidter_msg);
		getVcode = (Button) findViewById(R.id.regidter_get_vcode);
		vcodeTime = (Button) findViewById(R.id.regidter_get_vcode_time);
		submit = (Button) findViewById(R.id.regidter_submit);
		havazh = (TextView) findViewById(R.id.regidter_havezh);
		getVcode.setOnClickListener(this);
		vcodeTime.setOnClickListener(this);
		submit.setOnClickListener(this);
		havazh.setOnClickListener(this);
		
//		phone.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_phone_hover:R.drawable.loginico_phone);
//				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
//				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
//			}
//		});
//		passwd.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_password_hover:R.drawable.loginico_password);
//				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
//				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
//			}
//		});
//		vcode.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_code_hover:R.drawable.loginico_code);
//				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
//				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
//			}
//		});
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==901){
			if(appContext.isLogin()){
				finish();
			}else{
				UIUtil.ToastMessage(activity, "未登陆");
			}
		}
	}

	@Override
	public void onClick(View view) {
		msg.setText("");
		final String phoneStr = phone.getText().toString();
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.regidter_get_vcode_time:
			if(time60==0){
				time60 = 60;
				mHandler.sendEmptyMessage(1);
			}else{
				break;
			}
		case R.id.regidter_get_vcode:
			if(StringUtil.isEmpty(phoneStr)||!StringUtil.isPhone(phoneStr)){
				msg.setText("电话号码不正确");
				return;
			}
			if(getvd){
				return;
			}
			getvd = true;
			mHandler.sendEmptyMessage(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("phone", phoneStr);
			//map.put("type", "1");
			//final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "提交中，请稍后...", false);
			HttpService.postByText(URLs.USER_REGISTURE_VCODE, map, new TextHttpResponseHandler() {
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, String result) {
					//mProDialog.dismiss();
					getvd = false;
					try {
						JSONObject json = new JSONObject(result);
						Log.i("==vcode==", result);
						if(BaseTools.getFrom("status", json).equals("0")){
							vcodeStr = BaseTools.getFrom("data", json);
							getVcode.setVisibility(View.GONE);
							vcodeTime.setVisibility(View.VISIBLE);
						}else{
							msg.setText(BaseTools.getFrom("message", json));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					//mProDialog.dismiss();
					getvd = false;
					msg.setText("访问错误");
				}
			});
			break;
		case R.id.regidter_submit:
			try {
			if(StringUtil.isEmpty(phoneStr)||!StringUtil.isPhone(phoneStr)){
				msg.setText("电话号码不正确");
				return;
			}
			String vcodeStrTmp = vcode.getText().toString();
			if(StringUtil.isEmpty(vcodeStrTmp)){
				msg.setText("验证码不正确");
				return;
			}
			String passwdStr = passwd.getText().toString();
			if(StringUtil.isEmpty(passwdStr)||passwdStr.trim().length()<6){
				msg.setText("密码不合法，且不低于6位");
				return;
			}
			final Map<String, String> smap = new HashMap<String, String>();
			smap.put("phone", phoneStr.trim());
			smap.put("password", MD5.MD5Encode(passwdStr.trim()));
			smap.put("code", vcodeStrTmp.trim());
			HttpService.postByText(URLs.USER_REGISTURE_SUBMIT, smap, new TextHttpResponseHandler() {
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, String result) {
					try {
						JSONObject json = new JSONObject(result);
						Log.i("==vcode==", result);
						if(BaseTools.getFrom("status", json).equals("0")){
							LoginActivity.login(smap.get("phone"),smap.get("password"), activity, new AfterDo() {
								@Override
								public void afterDo(Activity activity) {
									activity.finish();
								}
							});
							
						}else if(BaseTools.getFrom("status", json).equals("909")){
							msg.setText("手机已注册");
						}else if(BaseTools.getFrom("status", json).equals("907")){
							msg.setText("验证码错误");
						}else{
							msg.setText("系统错误");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					msg.setText("访问错误："+arg2);
				}
			});
			} catch (Exception e1) {
				msg.setText("系统错误：加密失败！");
			}
			break;
		case R.id.regidter_havezh:
			UIUtil.openActivity(this, LoginActivity.class, null, 901);
			break;
		default:
			break;
		}
	}

}
